package com.xquant.trade.utils;
 

import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.Optional;

/**
 * @Author: xpp -_- -_-
 * @Date: 2021/6/18 11:22
 */
public class LoginErrorMap {
    static class LoginStamp {
        private Integer num;
        private Date lastLoginDate;

        public Integer getNum() {
            return num;
        }

        public void setNum(Integer num) {
            this.num = num;
        }

        public Date getLastLoginDate() {
            return lastLoginDate;
        }

        public void setLastLoginDate(Date lastLoginDate) {
            this.lastLoginDate = lastLoginDate;
        }

        public LoginStamp(Integer num, Date lastLoginDate) {
            this.num = num;
            this.lastLoginDate = lastLoginDate;
        }
    }

    public static final TimerExpireHashMap<String, LoginStamp> loginErrorMap = new TimerExpireHashMap<>();
    //    private static Map<String, LoginStamp> loginErrorMap = new ConcurrentHashMap<String, LoginStamp>();
//    private static Integer AccountLockTime = Integer.parseInt(ParamCache.getString("AccountLockTime"));
    private static Integer AccountLockTime = 3600;

    public static void addErrorLog(String ipAddressAndUserId) {
        Integer errorNum = getErrorLog(ipAddressAndUserId);
        LoginStamp loginStamp = null;
        if (errorNum > 0) {
            loginStamp = new LoginStamp(errorNum + 1, new Date());
        } else {
            loginStamp = new LoginStamp(1, new Date());
        }
        loginErrorMap.put(ipAddressAndUserId, loginStamp, 60L * AccountLockTime);
        loginErrorMap.setTimerExpireHashMapCallback((k, v) -> System.out.println(MessageFormat.format("Key {0} has expire!!", k)));
    }

    public static Integer getErrorLog(String ipAddressAndUserId) {
        LoginStamp loginStamp = loginErrorMap.get(ipAddressAndUserId);
        if (Optional.ofNullable(loginStamp).isPresent()) {
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String lastLoginDate = dateformat.format(loginStamp.getLastLoginDate());
            String today = dateformat.format(new Date());
            // 判断ts是否有效（token中的有效期为系统当前日-token生成时间相差86400秒以下即为有效）
            long seconds = 0;
            try {
                seconds = Duration.between(dateformat.parse(lastLoginDate).toInstant(), dateformat.parse(today).toInstant()).getSeconds();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (seconds > 60 * AccountLockTime) {
                loginErrorMap.remove(ipAddressAndUserId);
                return 0;
            }
            return loginStamp.getNum();
        }
        return 0;
    }

    public static void remove(String ipAddressAndUserId) {
        loginErrorMap.remove(ipAddressAndUserId);
    }
}
